package teama.logic;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import teama.bean.MailBean;
import teama.constant.Constant;

public abstract class MailSend {

	protected void send(MailBean bean) {

		String select = bean.getMainKind();

		String smtpHost;
		String mailHost;
		String smtpPort;
		String socketFactoryPort;

		if (Constant.smtpMap.containsKey(select)) {
			smtpHost = Constant.smtpMap.get(select)[0];
			mailHost = Constant.smtpMap.get(select)[0];
			smtpPort = Constant.smtpMap.get(select)[1];
			socketFactoryPort = Constant.smtpMap.get(select)[1];
		} else {
			smtpHost = bean.getHost();
			mailHost = bean.getHost();
			smtpPort = bean.getPort();
			socketFactoryPort = bean.getPort();
		}

		Properties objPrp=new Properties();
		objPrp.put(Constant.SMTP_HOST, smtpHost); // SMTPサーバ名
		objPrp.put(Constant.MAIL_HOST, mailHost); // 接続するホスト名
		objPrp.put(Constant.SMTP_PORT, smtpPort); // ポート番号
		objPrp.put(Constant.SMTP_AUTH, Boolean.TRUE.toString()); // 承認

		objPrp.put(Constant.SOCKET_FACTORY_PORT, socketFactoryPort); // SSL
		objPrp.put(Constant.SOCKET_FACTORY_CLASS, Constant.SSL_SOCKET_FACTORY);
		objPrp.put(Constant.SSL_SOCKET_FACTORY_FALLBACK, String.valueOf( false ) );

		// メールセッションを確立
	    Session session=Session.getDefaultInstance(objPrp,null);
	    // 送信メッセージを生成
	    MimeMessage objMsg=new MimeMessage(session);
	    Transport transport = null;
	    try {
	    	String to = bean.getTo();
	    	String cc = bean.getCc();
	    	String bcc = bean.getBcc();
	    	String from = bean.getFrom();
	    	String pass = bean.getPass();
	    	String subject = bean.getSubject();
	    	String content = bean.getContent();

	    	// 送信先（TOのほか、CCやBCCも設定可能）
	    	objMsg.setRecipients(Message.RecipientType.TO, to);
	    	objMsg.setRecipients(Message.RecipientType.CC, cc);
	    	objMsg.setRecipients(Message.RecipientType.BCC, bcc);

	    	// Fromヘッダ
	    	InternetAddress objFrm=new InternetAddress(from);

			objMsg.setFrom(objFrm);
			// 件名
			objMsg.setSubject(subject,"ISO-2022-JP");

			// 本文
			objMsg.setText(content,"ISO-2022-JP");

			// メール送信
			transport = session.getTransport("smtp");
			if (pass == null || !(0 < pass.length())) {
				transport.connect();
			} else {
				transport.connect(from, pass);
			}

			transport.sendMessage(objMsg, objMsg.getAllRecipients());

	    } catch (Throwable th) {
	    	th.printStackTrace();
	    } finally {
	    	try {
	    		if (transport != null) {
	    			transport.close();
	    		}
	    	} catch (Exception e) {
				// TODO: handle exception
			}

		}
	}

	public abstract void sendMail(MailBean bean);
}
